const bcrypt = require('bcryptjs')
const mysql = require('mysql2/promise')

async function main () {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'hezi5200',
    database: 'novel_platform'
  })

  try {
    // 检查管理员账号
    const [existing] = await connection.execute(
      'SELECT * FROM users WHERE email = ?',
      ['admin@novel.com']
    )

    if (existing.length === 0) {
      // 创建管理员账号
      const hashedPassword = await bcrypt.hash('admin123', 12)

      await connection.execute(
        'INSERT INTO users (username, email, password_hash, nickname, is_vip, coins) VALUES (?, ?, ?, ?, ?, ?)',
        ['admin', 'admin@novel.com', hashedPassword, '管理员', 1, 9999]
      )

      console.log('✅ 管理员账号创建成功！')
    } else {
      console.log('✅ 管理员账号已存在')
    }

    // 检查备用管理员账号
    const [existing2] = await connection.execute(
      'SELECT * FROM users WHERE email = ?',
      ['admin@example.com']
    )

    if (existing2.length === 0) {
      // 创建备用管理员账号
      const hashedPassword = await bcrypt.hash('123456', 12)

      await connection.execute(
        'INSERT INTO users (username, email, password_hash, nickname, is_vip, coins) VALUES (?, ?, ?, ?, ?, ?)',
        ['admin2', 'admin@example.com', hashedPassword, '管理员2', 1, 9999]
      )

      console.log('✅ 备用管理员账号创建成功！')
    } else {
      console.log('✅ 备用管理员账号已存在')
    }

    console.log('')
    console.log('🔑 管理员登录信息：')
    console.log('   主账号: admin@novel.com / admin123')
    console.log('   备用账号: admin@example.com / 123456')
    console.log('')

    // 显示所有用户
    const [users] = await connection.execute(
      'SELECT id, username, email, nickname, is_vip, coins FROM users'
    )

    console.log('📋 所有用户:')
    console.table(users)
  } catch (error) {
    console.error('错误:', error.message)
  }

  await connection.end()
  process.exit(0)
}

main()
